package com.lg.rpc.common.protocol.codec;

import com.lg.rpc.common.protocol.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * RPC解码器
 *
 * @author by Mr. Li 2020/5/21 19:23
 */
@Slf4j
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> genericClass;

    public RpcDecoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);
        log.debug("RpcDecoder is running....");
        out.add(SerializationUtil.deserialize(data, genericClass));
        //Object obj = JsonUtil.deserialize(data,genericClass); // Not use this, have some bugs
    }
}
